<?php
class XMLParser {
	var $xml;
	var $data;

	function XMLParser($data) {
		$this->xml = xml_parser_create();
		xml_set_object($this->xml, $this);
		xml_set_element_handler($this->xml, 'startHandler', 'endHandler');
		xml_set_character_data_handler($this->xml, 'dataHandler');
		$this->parse($data);
	}

	function parse($data) {
		$parse = xml_parse($this->xml, $data, sizeof($data));

		if (!$parse) {
			die(sprintf("XML error: %s at line %d",
			xml_error_string(xml_get_error_code($this->xml)),
			xml_get_current_line_number($this->xml)));
			xml_parser_free($this->xml);
		}
		return true;
	}

	function startHandler($parser, $name, $attributes) {
		$name = strtolower($name);
		//$data['name'] = $name;
		$data = '';
		if ($attributes) { $data['attributes'] = $attributes; }
		$this->data[] = $data;
	}

	function dataHandler($parser, $data) {
		if ($data = trim($data)) {
			$index = count($this->data) - 1;
			$this->data[$index] .= $data;
		}
	}

	function endHandler($parser, $name) {
		$name = strtolower($name);
		if (count($this->data) > 1) {
			$data = array_pop($this->data);
			$index = count($this->data) - 1;
			$this->data[$index][$name] = $data;
		}
	}
}